package cn.txm.product.service.impl;

import cn.txm.basic.service.impl.BaseServiceImpl;
import cn.txm.product.domain.Shopcart;
import cn.txm.product.mapper.ShopcartMapper;
import cn.txm.product.service.IShopcartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.math.BigDecimal;
import java.util.List;

@Service
public class ShopcartServiceImpl extends BaseServiceImpl<Shopcart> implements IShopcartService {

    @Autowired

    private ShopcartMapper shopcartMapper;
    /**
     * 重写add方法，先通过user_id和product_id查询购物车表数据
     *  查不到：就直接计算小计金额，直接save
     *  查到了：就累加购买数量，和小计金额，然后update
     * @param shopcart
     */
    @Override
    @Transactional
    public void add(Shopcart shopcart) {
        //计算小计金额
        shopcart.setAmount(shopcart.getPrice().multiply(new BigDecimal(shopcart.getBuycount())));
        //1.先通过user_id和product_id查询购物车表数据
        Shopcart sc = shopcartMapper.findByUserIdAndProductId(shopcart.getUser_id(), shopcart.getProduct_id());
        //如果没有查到数据，就证明是新增
        if(sc==null){
            shopcartMapper.save(shopcart);
        }else {
            //修改购买数量
            sc.setBuycount(sc.getBuycount() + shopcart.getBuycount());
            //计算小计金额
            sc.setAmount(sc.getAmount().add(shopcart.getAmount()));
            shopcartMapper.update(sc);
        }


    }
    /**
     * 根据前台当前登录用户id，查询它的购物车数据
     * @param user_id
     * @return
     */
    @Override
    public List<Shopcart> getMyShopcarts(Long user_id) {
        return shopcartMapper.getMyShopcarts(user_id);
    }
}
